﻿using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Data.Objects;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using BugTracker.Models;
using BugTracker.Helper;

namespace BugTracker.Helper
{
    public class ErrorLogHelpers
    {
        Bug_db toget = new Bug_db();
        SessionHelper sesshelp = new SessionHelper();
        ErrorLog errlog = new ErrorLog();

        public int userlog;
        private static string sesid = HttpContext.Current.Session.SessionID;

        public int ErrorLog_Init()
        {
            string ipadd = sesshelp.Session_GetIPAddress();
            string browser = sesshelp.Session_GetBrowserType();
            string today = sesshelp.Session_GetDateToday();

            var log = (from logs in toget.ErrorLogs
                       where logs.datetoday == today && logs.ipaddress == ipadd
                       && logs.sessionid_token == sesid
                       select logs).SingleOrDefault();



            if (log == null)
            {
                errlog.ipaddress = ipadd;
                errlog.sessionid_token = sesid;
                errlog.browser = browser;
                errlog.datetoday = today;
                errlog.log_attempt = 1;

                toget.ErrorLogs.Add(errlog);
                toget.SaveChanges();

                return errlog.erroridPK;
            }
            else
            {
                log.ipaddress = ipadd;
                log.browser = browser;
                log.sessionid_token = sesid;
                log.datetoday = today;

                toget.Entry(log).State = EntityState.Modified;
                toget.SaveChanges();

                return log.erroridPK;
            }
        }

        public ErrorLog Check_ErrorLog()
        {

            string browser = sesshelp.Session_GetBrowserType();
            string ipadd = sesshelp.Session_GetIPAddress();
            string today = sesshelp.Session_GetDateToday();
            //string sesid = sesshelp.Session_Info().sessionid_token;

            var log = (from logs in toget.ErrorLogs
                       where logs.browser == browser 
                       && logs.datetoday == today
                       && logs.ipaddress == ipadd 
                       && logs.sessionid_token == sesid
                       select logs).SingleOrDefault();

            if (log != null)
            {
                return log;
            }
            else
            {
                return null;
            }
        }
    }
}